package com.example.gbuffer.Component.Model;

import android.opengl.GLES32;
import android.util.Log;

import com.example.gbuffer.Component.Shader;
import com.example.gbuffer.Utils.GLBufferWrapper;

import java.nio.FloatBuffer;

public class QuadModel extends Model{

    private int[] vaoIds = new int[1];  // 用于存储 VAO ID
    private int[] vboIds = new int[1];
    private FloatBuffer m_vertex_buffer;


    @Override
    public void load(String model_path) {

    }
    public void load() {
        generateTestVertices();

        // 绑定顶点数据
        GLES32.glGenVertexArrays(1, vaoIds, 0); // 生成 VAO
        GLES32.glBindVertexArray(vaoIds[0]);    // 绑定 VAO

        Log.d("QuadModel", "load: vao id = " + vaoIds[0]);

        GLES32.glGenBuffers(1, vboIds, 0);
        GLES32.glBindBuffer(GLES32.GL_ARRAY_BUFFER, vboIds[0]);
        GLES32.glBufferData(GLES32.GL_ARRAY_BUFFER, m_vertex_buffer.capacity() * Float.BYTES, m_vertex_buffer, GLES32.GL_STATIC_DRAW);      // position


        // 设置顶点属性指针
        // position
        GLES32.glEnableVertexAttribArray(0);
        GLES32.glVertexAttribPointer(0, 3, GLES32.GL_FLOAT, false, 5 * Float.BYTES, 0);

        // texture
        GLES32.glEnableVertexAttribArray(1);
        GLES32.glVertexAttribPointer(1, 2, GLES32.GL_FLOAT, false, 5 * Float.BYTES, 3*Float.BYTES);

        // 解绑
        GLES32.glBindVertexArray(0);
        GLES32.glDisableVertexAttribArray(0);
        GLES32.glDisableVertexAttribArray(1);
    }


    @Override
    public void draw(Shader shader) {
        shader.use();
        // 绑定顶点对象
        GLES32.glBindVertexArray(vaoIds[0]);

        GLES32.glEnableVertexAttribArray(0);
        GLES32.glEnableVertexAttribArray(1);


        // 绘制
        GLES32.glDrawArrays(GLES32.GL_TRIANGLES, 0, 6);

        // 解绑
        GLES32.glBindVertexArray(0);
        GLES32.glDisableVertexAttribArray(0);
        GLES32.glDisableVertexAttribArray(1);

        GLES32.glBindTexture(GLES32.GL_TEXTURE_2D, 0);
    }

    /**
     * @brief 生成顶点数据
     */
    private void generateTestVertices()
    {
        m_vertex_buffer = GLBufferWrapper.WrapFloat(new float[]{

                1.0f,  1.0f, 0.0f,  1.0f, 1.0f, // top-right
                1.0f, -1.0f, 0.0f,  1.0f, 0.0f, // bottom-right
                -1.0f, -1.0f, 0.0f,  0.0f, 0.0f,  // bottom-left

                -1.0f,  1.0f, 0.0f,  0.0f, 1.0f, // top-left
                 1.0f,  1.0f, 0.0f,  1.0f, 1.0f, // top-right
                -1.0f, -1.0f, 0.0f,  0.0f, 0.0f, // bottom-left

        });
    }

}
